package cn.gogpay.duoim.sdk.service;

import cn.gogpay.duoim.sdk.constant.IMApis;
import cn.gogpay.duoim.sdk.constant.IMRespCode;
import cn.gogpay.duoim.sdk.exception.IMSDKException;
import cn.gogpay.duoim.sdk.model.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import okhttp3.Request;

import java.util.List;
import java.util.Optional;

/**
 * 群组
 */
public class IMGroupService {

    /**
     * 邀请用户进群
     *
     * @param req 请求
     * @return 响应
     */
    public IMRespResult<List<InviteUserToGroupResp>> inviteUserToGroup(String token, InviteUserToGroupReq req) {
        String param = JSON.toJSONString(req);
        Request request = IMApiFactory.buildLoginRequest(token, param, IMApis.INVITE_USER_TO_GROUP);
        String data = IMApiFactory.callRequest(request);

        TypeReference<IMRespResult<List<InviteUserToGroupResp>>> typeReference = new TypeReference<IMRespResult<List<InviteUserToGroupResp>>>() {
        };

        IMRespResult<List<InviteUserToGroupResp>> result;
        try {
            result = JSON.parseObject(data, typeReference);
        } catch (Exception e) {
            throw new IMSDKException(IMRespCode.parse(), e.getMessage());
        }
        return result;
    }

    /**
     * 设置群信息
     *
     * @param req 请求
     * @return 响应
     */
    public IMRespResult<String> setGroupInfo(String token, SetGroupInfoReq req) {
        String param = JSON.toJSONString(req);
        Request request = IMApiFactory.buildLoginRequest(token, param, IMApis.SET_GROUP_INFO);
        String data = IMApiFactory.callRequest(request);

        TypeReference<IMRespResult<String>> typeReference = new TypeReference<IMRespResult<String>>() {
        };

        IMRespResult<String> result;
        try {
            result = JSON.parseObject(data, typeReference);
        } catch (Exception e) {
            throw new IMSDKException(IMRespCode.parse(), e.getMessage());
        }
        return result;
    }

    /**
     * 把用户踢出群组
     *
     * @param req 请求
     * @return 响应
     */
    public IMRespResult<List<KickGroupMemberResp>> kickGroupMember(String token, KickGroupMemberReq req) {
        String param = JSON.toJSONString(req);
        Request request = IMApiFactory.buildLoginRequest(token, param, IMApis.KICK_GROUP_MEMBER);
        String data = IMApiFactory.callRequest(request);

        TypeReference<IMRespResult<List<KickGroupMemberResp>>> typeReference = new TypeReference<IMRespResult<List<KickGroupMemberResp>>>() {
        };

        IMRespResult<List<KickGroupMemberResp>> result;
        try {
            result = JSON.parseObject(data, typeReference);
        } catch (Exception e) {
            throw new IMSDKException(IMRespCode.parse(), Optional.ofNullable(e.getMessage()).orElse(""));
        }
        return result;
    }
}
